<template>
<div class="SwPaging" v-show="total">
  <a :class="{disabled: pagingConfig.current <= 1}" @click="jumpPage(pagingConfig.prev)">{{lang['prev']}}</a>
  <a v-show="pagingConfig.left >= 2" @click="jumpPage(1)">1</a
  ><a v-show="pagingConfig.left >= 3">...</a
  ><a v-for="item in pagingConfig.list" v-text="item.no" :class="{active: item.isCurrent}" @click="jumpPage(item.no)"></a
  ><a v-show="pagingConfig.right <= pagingConfig.pageTotal - 2">...</a
  ><a v-show="pagingConfig.right <= pagingConfig.pageTotal - 1" v-text="pagingConfig.pageTotal" @click="jumpPage(pagingConfig.pageTotal)"></a>
  <a :class="{disabled: pagingConfig.current >= pagingConfig.pageTotal}" @click="jumpPage(pagingConfig.next)">{{lang['next']}}</a>
</div>
</template>

<script>
import PagingConfig from '@/utils/PagingConfig.js'

export default {
  data () {
    return {
      isInited: false,
      pagingConfig: {list: []}
    }
  },
  props: [
    'lang',
    'pageSize',
    'pageRange',
    'total',
    'pageIndex'
  ],
  watch: {
    // total有变动则要重新渲染页码
    total (nv) {
      if (nv) {
        // 获取页码配置
        PagingConfig.init({
          pageSize: this.pageSize,
          pageRange: this.pageRange,
          total: this.total
        })

        // total变更要重新渲染
        if (this.isInited) {
          this.renderNo(this.pagingConfig.current)
        }

        !this.isInited && this.jumpPage(1)
        this.isInited = true
      }
    },
    // 支持由父组件控制跳页
    pageIndex (nv) {
      this.pagingConfig.current = nv // 校正页码
      this.renderNo(nv)
    }
  },
  methods: {
    renderNo (no) {
      this.pagingConfig = PagingConfig.getConfig(no)
      this.pagingConfig.list = []
      for (var i = this.pagingConfig.left; i <= this.pagingConfig.right; i++) {
        this.pagingConfig.list.push({
          no: i,
          isCurrent: i === this.pagingConfig.current
        })
      }
    },
    jumpPage (no) {
      if (this.pagingConfig.left && (no === this.pagingConfig.current || no < 1 || no > this.pagingConfig.pageTotal)) return
      this.renderNo(no)

      // 默认第一页，不发送跳页事件
      this.isInited && this.$emit('jumpPage', no)
    }
  },
  mounted () {

  }
}
</script>

<style lang="less">
.SwPaging {
  clear: both;
  text-align: center;
  padding: 30px 0;

  a {
    display: inline-block;
    margin: 0 2px;
    padding: 0 12px;
    height: 28px;
    line-height: 28px;
    border: solid 1px rgba(255,255,255,.5);
    border-radius: 3px;
    color: rgba(255,255,255,.5);
  }
  a:hover, a.active {
    color: #3874c8;
    border-color: #3874c8;
  }
  a.disabled {
    color: rgba(255,255,255,.5);

    &:hover, &.active {
      background: transparent;
      color: rgba(255,255,255,.5);
    }
  }
}
</style>
